package com.simon.webviewjs;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author: YDS
 * @describe: 暂无描述
 * @date: 2020-4-29 10:19:06
 */
@SuppressWarnings("all")
public class MainActivity extends AppCompatActivity {

    private WebView webview;
    private Button bt_location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt_location = findViewById(R.id.bt_location);
        webview = findViewById(R.id.webview);

        bt_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview.post(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject object = new JSONObject();
                        try {
                            object.put("type", "location");
                            object.put("cityId", "024");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String cityId = object.toString();
                        webview.evaluateJavascript("javascript:requestDataFromAndroid(" + cityId + ")", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                //此处为 js 返回的结果
                                Log.i("Simon", "onReceiveValue = " + value);
                            }
                        });
                    }
                });
            }
        });

        initView();
    }

    private void initView() {
        WebSettings settings = webview.getSettings();
        // 设置与Js交互的权限
        settings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 网页内容的宽度自适应屏幕
        settings.setLoadWithOverviewMode(true);
        // 设置此属性，可任意比例缩放。
        settings.setUseWideViewPort(true);
        // 是否保存表单数据
        settings.setSaveFormData(false);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        // 是否启动应用缓存
        settings.setAppCacheEnabled(false);
        // com.tencent.smtt.sdk.LOAD_NO_CACHE com.tencent.smtt.sdk.LOAD_DEFAULT
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        // 页面加载好以后，再放开图片
        settings.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        settings.setDomStorageEnabled(true);
        // 排版适应屏幕 com.tencent.smtt.sdk.
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
        settings.setSupportMultipleWindows(true);
        // 是否手势返回
        settings.setMediaPlaybackRequiresUserGesture(false);
        // 设置字体默认缩放大小
        settings.setTextZoom(100);
        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//com.tencent.smtt.sdk.
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // JS通过WebView调用Android 参数1：JS调用android中方法对象 参数2：映射到js中的test对象
        webview.addJavascriptInterface(new JsUtil(), "android");
        webview.loadUrl("http://192.168.1.167:8080/#/?token=EZ8XX5VZO408KWOW048S8GKWOOCCKOG");
//        webview.loadUrl("file:///android_asset/index.html");

        //设置响应js 的Alert()函数
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.i("Simon", "onJsAlert = " + message);
                return false;
            }
        });
    }

    /**
     * js交互类
     */
    class JsUtil extends Object {

        @JavascriptInterface
        public void requestDataFromJs(String data) {
            Log.i("Simon", "requestDataFromJs = " + data);
        }
    }

}
